﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using NPOI.HSSF.UserModel;

namespace LX.Web.Excel
{
    public class ExcelDocument
    {
        public String TemplateFilePath { get; set; }
        private IWorkbook workbook;

        public ExcelDocument()
        {

        }

        public ExcelDocument(string path)
        {
            TemplateFilePath = path;
        }

        private IWorkbook GetExcelDocument()
        {
            if (workbook == null)
            {
                using (FileStream fs = System.IO.File.OpenRead(TemplateFilePath))  //打开myxls.xls文件
                {
                    try
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    catch
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                }
            }
            
            return workbook;
        }

        public byte[] GetBinaryData()
        {
            MemoryStream ms = new MemoryStream();
            GetExcelDocument().Write(ms);
            byte[] data = ms.ToArray();
            ms.Flush();
            return data;
        }

        public ExcelSheet GetSheet(string name)
        {
            return new ExcelSheet(GetExcelDocument().GetSheet(name));
        }
        public ExcelSheet GetSheet(int index)
        {
            return new ExcelSheet(GetExcelDocument().GetSheetAt(index));
        }
        public ExcelSheet AddSheet(string name)
        {
            var sheet=GetExcelDocument().CreateSheet(name);
            return new ExcelSheet(sheet);
        }
    }
}
